/* eslint-disable @typescript-eslint/ban-types */
import { useEffect, useState } from "react";
import Header from "@/components/Header";
import {
  Table,
  TableColumnsType,
  Form,
  DatePicker,
  Modal,
  Row,
  Col,
  Radio,
  TreeSelect,
  Input,
} from "antd";
import "./index.scss";

import { DataType, FieldData, OrderSchema } from "../../api/types";
import {
  getMidList,
  getStateList,
  getSourceList,
  getOrderList,
  getUserList,
  getStoreList,
  updateOrder,
} from "@/api/index";
import Search from "./search";

// const data: DataType[] = [
//   {
//     key: 1,
//     createTime: {
//       date: "2023-03-01", // 创建时间日期
//       orderId: "190621030", // 订单号
//     }, // 创建时间
//     uid: {
//       name: "张三", // 承租人姓名
//       phone: 17332808337, // 承租人电话
//     }, // 承租人id
//     collection_return_time: {
//       collectionTime: "2023-03-01", // 取车时间日期
//       returnTime: "2023-03-07", // 还车时间日期
//     }, // 取还车时间
//     collection_return_address: {
//       collectionAddress: "北京市朝阳区xxx店", // 取车地址
//       returnAddress: "上海市浦东新区xx店", // 还车地址
//     }, // 取还车地址
//     leaseTime: "30天", // 租期
//     mid: {
//       id: 123456789, // 车型id
//       name: "大众", // 车型名称
//     }, // 车型id
//     rent: 1000, // 支付金额
//     deposit: 2000, // 押金金额
//     state: {
//       id: 1, // 订单状态id
//       name: "已取消", // 订单状态名称
//       state: true, // 订单状态 1进行中 0已取消或逾期
//     }, // 订单状态
//   },
// ];
export default function Order() {
  // 订单信息
  const [orderList, setOrderList] = useState<DataType[] | []>([]);
  // 用户信息
  const [userList, setUserList] = useState<
    { value: number; title: string }[] | []
  >([]);
  // 车型信息
  const [midList, setMidList] = useState<
    { value: number; title: string }[] | []
  >([]);
  // 订单状态
  const [state, setState] = useState<{ value: number; title: string }[] | []>(
    []
  );
  // 订单来源
  const [source, setSource] = useState<{ value: number; title: string }[] | []>(
    []
  );
  // 车型信息
  const [store, setStore] = useState<{ value: number; title: string }[] | []>(
    []
  );
  // 搜索信息
  const [search, setSearch] = useState<OrderSchema>({});
  // 搜索form的form
  const [searchForm] = Form.useForm();
  // 搜索数据修改
  const changeSearch = (str: string, value: string) => {
    setSearch({ ...search, [str]: value });
    console.log(str, value, search);
  };
  const changeOrden = async () => {
    const data = await getOrderList(search);
    console.log(data);
  };
  // 打开form表单的控件
  const [create, setCreate] = useState(true);
  // form表单数据
  const [form, setForm] = useState({});
  // from表单 字段更新后执行的方法
  const changeForm = (changedFields: FieldData[] | string, value?: string) => {
    setForm(() => {
      console.log(changedFields, form);
      if (typeof changedFields == "string") {
        return {
          ...form,
          [changedFields]: value,
        };
      } else if (
        changedFields[0].name[0] == "collectionTime" ||
        changedFields[0].name[0] == "returnTime"
      ) {
        return form;
      } else
        return {
          ...form,
          [changedFields[0].name[0]]: changedFields[0].value,
        };
    });
  };

  // // 各种请求的信息的测试数据
  // const users = [
  //   { title: "张无忌", value: "1" },
  //   { title: "张无1", value: "2" },
  //   { title: "张三1", value: "3" },
  //   { title: "张三年", value: "4" },
  // ];

  useEffect(() => {
    const get = async function () {
      const orderDate = await getOrderList(search);
      setOrderList(orderDate.data.orderList);
      console.log(orderDate.data, "orderdata");

      const storeList = await getStoreList();
      setStore(() => {
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        return storeList.data.data.map((item: any) => {
          return {
            title: `${item.name}(${item.address}/${item.detailAds})`,
            value: item.id,
          };
        });
      });
      const userList = await getUserList();
      setUserList(() => {
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        return userList.data.data.map((item: any) => {
          return { title: item.name, value: item.id };
        });
      });
      const midData = await getMidList();
      setMidList(() => {
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        return midData.data.data.map((item: any) => {
          return {
            title: item.vname + "/" + item.platenumber,
            value: item.veid,
          };
        });
      });
      const stateDate = await getStateList();
      setState(() => {
        return stateDate.data.data.map((item: { name: string; id: number }) => {
          return {
            title: item.name,
            value: item.id,
          };
        });
      });
      const sourceDate = await getSourceList();
      setSource(() => {
        return sourceDate.data.data.map(
          (item: { name: string; id: number }) => {
            return {
              title: item.name,
              value: item.id,
            };
          }
        );
      });
    };
    get();
  }, []);
  const columns: TableColumnsType<DataType> = [
    {
      title: "创建时间",
      width: 170,
      dataIndex: "createTime",
      className: "fontWeight700",
      render: (data) => (
        <>
          <div>{data.date}</div>
          <div>
            订单号:<span className="color_1EACE8">{data.orderId}</span>
          </div>
        </>
      ),
    },
    {
      title: "承租人",
      width: 150,
      dataIndex: "uid",
      className: "fontWeight700",
      render: (data) => (
        <>
          <div>{data.name}</div>
          <div className="underline">{data.phone}</div>
        </>
      ),
    },
    {
      title: "取还车时间",
      width: 180,
      dataIndex: "collection_return_time",
      className: "collection_return_car",
      render: (data) => (
        <>
          <div className="fontWeight700 color_FB6638">
            <span className="collection_return_car background_FB6638">
              取车
            </span>
            {data.collectionTime}
          </div>
          <div className="fontWeight700 color_666">
            <span className="collection_return_car background_666">还车</span>
            {data.returnTime}
          </div>
        </>
      ),
    },
    {
      title: "取还车地址",
      width: 280,
      dataIndex: "collection_return_address",
      className: "collection_return_car",
      render: (data) => (
        <>
          <div className="fontWeight700 color_FB6638">
            <span className="collection_return_car background_FB6638">
              取车
            </span>
            {data.collectionAddress}
          </div>
          <div className="fontWeight700 color_666">
            <span className="collection_return_car background_666">还车</span>
            {data.returnAddress}
          </div>
        </>
      ),
    },
    {
      title: "租期",
      width: 150,
      dataIndex: "leaseTime",
    },
    {
      title: "预订车型",
      width: 150,
      dataIndex: "mid",
      render: (data) => <>{data.name}</>,
    },
    {
      title: "支付金额",
      width: 150,
      dataIndex: "rent",
      render: (data) => <>￥{data}</>,
    },
    {
      title: "押金金额",
      width: 150,
      dataIndex: "deposit",
      render: (data) => <>￥{data}</>,
    },
    {
      title: "订单状态",
      width: 150,
      dataIndex: "state",
      className: "orderState",
      render: (_, data) => {
        return (
          <>
            {data.state.state === true ? (
              <span className="fontWeight700 background_FB6638" style={{}}>
                {data.state.name}
              </span>
            ) : data.state.name == "已取消" ? (
              <span className="fontWeight700 toCancel">{data.state.name}</span>
            ) : (
              <span className="fontWeight700 color_666">待还车</span>
            )}
          </>
        );
      },
    },
    {
      title: "合同",
      width: 150,
      dataIndex: "contract",
      className: "contract",
      render: (_, data) => (
        <span>{data.state.state === true ? "打印合同" : ""}</span>
      ),
    },
    {
      title: "操作",
      width: 150,
      dataIndex: "operate",
      render: (_, data) => (
        <div className="orderOperate">
          <button
            onClick={() => {
              updateOrder(data.key, {
                state: state.find(
                  (item: { value: number; title: string }) =>
                    item.title == "已取车"
                )?.value,
              });
            }}
          >
            取车
          </button>
          <br></br>
          <button>取消订单</button>
          <br></br>
          <button>修改订单</button>
          <br></br>
          <button>订单日志</button>
        </div>
      ),
    },
  ];
  return (
    <div className="storeBigBox">
      <Header title="订单列表" />
      <Search
        midList={midList}
        state={state}
        source={source}
        searchForm={searchForm}
        changeSearch={changeSearch}
      />
      <div className="rightBtn">
        <button
          onClick={() => {
            console.log(1);
            searchForm.resetFields();
            // setSearch({ state: "all", source: "all", type: "all" });
            // console.log(search);
          }}
        >
          清除条件
        </button>
        <button>导出报表</button>
        <button
          onClick={() => {
            console.log("创建订单");
            setCreate(true);
          }}
        >
          + 创建订单
        </button>
      </div>
      <div className="storeContent">
        <Table columns={columns} dataSource={orderList} scroll={{ y: 350 }} />
      </div>
      <Modal
        open={create}
        title="新增订单"
        wrapClassName="orderModal"
        width={800}
        onOk={() => {
          setCreate(false);
          setForm({});
        }}
        onCancel={() => {
          console.log("onCancel");
          setForm({});
          console.log(midList);
          setCreate(false);
        }}
      >
        <Form
          name="create"
          style={{ maxWidth: 600 }}
          onFieldsChange={(e) => changeForm(e)}
        >
          <Row>
            <Col span={24}>
              <Form.Item name="uid" label="用户信息">
                <TreeSelect
                  // style={{ width: "100%" }}
                  // value={user}
                  // dropdownStyle={{ maxHeight: 800 }}
                  placeholder="请选择用户（可搜索）"
                  allowClear
                  onChange={(e) => {
                    console.log(1, e);
                  }}
                  treeData={userList}
                ></TreeSelect>
              </Form.Item>
            </Col>
          </Row>
          <Row>
            <Col span={24}>
              <Form.Item name="orderSource" label="订单来源">
                <Radio.Group
                  defaultValue={"a"}
                  className="order-source-radio"
                  style={{ width: "800px", padding: "0" }}
                >
                  {source.map((item) => {
                    return (
                      <Radio value={item.value} key={item.value}>
                        {item.title}
                      </Radio>
                    );
                  })}
                </Radio.Group>
              </Form.Item>
            </Col>
          </Row>
          <Row>
            <Col span={24}>
              <Form.Item name="collectionAddress" label="取车门店">
                <TreeSelect
                  placeholder="请选择取车门店（可搜索）"
                  allowClear
                  onChange={(e) => {
                    console.log(1, e);
                  }}
                  treeData={store}
                ></TreeSelect>
              </Form.Item>
            </Col>
          </Row>
          <Row>
            <Col span={24}>
              <Form.Item name="returnAddress" label="还车门店">
                <TreeSelect
                  placeholder="请选择还车门店（可搜索）"
                  allowClear
                  onChange={(e) => {
                    console.log(1, e);
                  }}
                  treeData={store}
                ></TreeSelect>
              </Form.Item>
            </Col>
          </Row>
          <Row>
            <Col span={24}>
              <Form.Item name="mid" label="预定车辆">
                <TreeSelect
                  placeholder="请选择预定车型（可搜索）"
                  allowClear
                  onChange={(e) => {
                    console.log(1, e);
                  }}
                  treeData={midList}
                ></TreeSelect>
              </Form.Item>
            </Col>
          </Row>
          <Row>
            <Col span={12}>
              <Form.Item name="collectionTime" label="取车日期">
                <DatePicker
                  onChange={(_, v) => {
                    changeForm("collectionTime", v);
                  }}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="returnTime" label="还车日期">
                <DatePicker
                  onChange={(_, v) => {
                    changeForm("returnTime", v);
                  }}
                />
              </Form.Item>
            </Col>
          </Row>
          <Row>
            <Col span={24}>
              <Form.Item name="notes" label="备注信息">
                <Input />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>
    </div>
  );
}
